package com.hao.epidemic_prevention.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hao.epidemic_prevention.bean.User;
import com.hao.epidemic_prevention.service.UserService;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Descroption 莞工中央验证
 * @Author hao
 * @Date 2021/6/12 19:06
 **/

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    // 设置应用系统的AppID，每个应用都不同，你要先去申请注册
    private static String appId = "javaee";

    // 设置应用系统的appSecret，每个应用都不同，你要先去申请注册
    private static String appSecret = "b3b52e43ccfd";

    // '中央认证登录页
    private static String CAS_Server = "https://cas.dgut.edu.cn/";    //要换你自己的
    // -----------https://cas.zemcho.com/       http://localhost:8088/login/dgut/  https://cas.dgut.edu.cn/
    private static String casLoginUrl = "https://cas.dgut.edu.cn/?appid=" + appId;   ////要换你自己的

    // '中央认证兑票页
    private static String httpService = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";    //不用换

    // 获取用户信息
    private static String userInfoService = "https://cas.dgut.edu.cn/oauth/getUserInfo";   //不用换

    /*
     *
     * 1 第一步，用户发起登录，获取token
     * 用户发起用登录，APP端携带appid请求服务端，服务端验证app合法性，app合法性通过后用户输入账号密码提交，中央认证验证合法性后
     *
     * 2第二步，通过token获取access_token和openid
     * -APP端获取到token，利用token、appid和appsecret去获取access_token和openid
     *
     * 3第三步，通过access_token和openid获取个人信息
     */
    //@ResponseBody
    @CrossOrigin("*")
    @RequestMapping(value = "/login/dgut")
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        // 1从中央验证系统获取token
        String token = request.getParameter("token");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("token==============================" + token);
        // 没有Token，把用户重定向到中央认证登陆页
        if (token == null || "".equals(token)) {

            System.out.println("token为空格");
            // 跳到中央登录登录验证系统，这个异常判断
            response.sendRedirect(casLoginUrl);
            return null;
//            return casLoginUrl;
//            return new JSONResult(500, "获取token", casLoginUrl);
        } else {
            // 有票，开始兑票------第二步，通过token获取access_token和openid
            String ip = "172.27.15.28";
            System.out.println("token===" + token);
            String userIp = request.getLocalAddr();
            System.out.println("userIp===" + userIp);
            // 开始访问接口，验证token值
            Map<String, String> userInfo = postToken(token, userIp);  //这就是中央认证后你拿到的用户信息了
            User loginUser = new User(userInfo.get("name"), userInfo.get("username"),
                    userInfo.get("group"), userInfo.get("faculty"), userInfo.get("faculty_title"));

            if(userInfo.get("name") == null || userInfo.get("username") == null || userInfo.get("group") == null ||
                    userInfo.get("faculty") == null || userInfo.get("faculty_title") == null) {
                model.addAttribute("msg", "请完整登录！");
                return "fail";
            }

            User user = null;
            try {
                user = userService.getUser(loginUser);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (user == null) {
                Boolean result = userService.addUser(loginUser);
                if (result == false) {
                    model.addAttribute("msg", "添加失败，请联系管理员");
                    return "fail";
//                    return new JSONResult(500, "添加失败，请联系管理员", null);
                }
                //return new JSONResult(500, "添加失败，请联系管理员", null);

            }
            model.addAttribute("user", loginUser);
            return "index";
//            return new JSONResult(200, "登录成功", userInfo);
//            return new JSONResult(200, "登录成功", userInfo);
        }

    }

    /*
     * 2第二步，通过token获取access_token和openid
     * -APP端获取到token，利用token、appid和appsecret去获取access_token和openid
     *
     * 3第三步，通过access_token和openid获取个人信息
     */
    private Map<String, String> postToken(String token, String useip) throws ParseException, IOException {
        String myToken = token;
        String url = httpService;
        Map<String, String> userInfo  =   new HashMap<String,String>();
        //HttpClient httpClient = new DefaultHttpClient();
        HttpClient httpClient = GetHttpClient.getHttpClient();
        String json = jsonMethod(token, useip, appId, appSecret);
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        if(content != null || "".equals(content)){
            Map<String, String> map = JSON.parseObject(content, Map.class);
            String openid = map.get("openid");
            String accessToken = map.get("access_token");
            if(openid != null || "".equals(openid)){
                userInfo = getUserInfo(accessToken,openid);
                System.out.println("userInfo=="+userInfo);
            }
        }
        post.releaseConnection();
        System.out.println("postToken=="+content);
        return userInfo;

    }

    /*
     * 第三步：通过access_token和openid获取个人信息
     */
    private Map<String, String> getUserInfo(String aaccessToken, String openid) throws ParseException, IOException {
        Map<String, String> infoMap = new HashMap<String,String>();
        //HttpClient httpClient = new DefaultHttpClient();
        HttpClient httpClient = GetHttpClient.getHttpClient();
        HttpPost post = new HttpPost(userInfoService);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", aaccessToken);
        jsonObject.put("openid", openid);
        String jsonstr = JSONObject.toJSONString(jsonObject);
        StringEntity postingString = new StringEntity(jsonstr);// jsonstr传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        System.out.println("getUserInfocontent=="+content);
        if(content != null || "".equals(content)){
            ////获取用户信息
            Map<String, String> map = JSON.parseObject(content, Map.class);
            System.out.println("map=="+map);
            String username = map.get("username");
            String name = map.get("name");
            String group = map.get("group");

            int begin = content.indexOf("\"faculty\":") + 10;
            int end = begin;

            for(int i = begin; i < content.length(); i++) {
                if(content.charAt(i) == ',') break;
                else end ++;
            }

            String faculty = content.substring(begin,end);
            String faculty_title = map.get("faculty_title");

//			BeanUtils.copyProperties(source, target);
            if(username != null || "".equals(username)){
                infoMap.put("username",username);
                infoMap.put("name",name);
                infoMap.put("group",group);
                infoMap.put("faculty",faculty);
                infoMap.put("faculty_title",faculty_title);
            }
        }
        post.releaseConnection();
        return infoMap;
    }

    /*
     * 参数名 是否必须 类型 说明
     *  token 是 string
     *  上一步获取的token
     *  appid 是 string appid appsecret
     * 是 string app密钥 userip 是 string ip地址
     */
    public static String jsonMethod(String token, String userip, String appid, String appsecret) {
        System.out.println("userip==" + userip);
        String localIp = "";
        // 当在服务器上本地测试时，用户访问ip会变成10.0.2.2，而中央认证将获取到本地服务器ip，故需要手动替换
        if ("10.0.2.2".equals(userip)) {
            localIp = "172.27.15.28";
        } else {
            localIp = userip;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("appid", appid);
        jsonObject.put("appsecret", appsecret);
        jsonObject.put("userip", localIp);
        String jsonstr = JSONObject.toJSONString(jsonObject);
        System.out.println("jsonMethod的jsonstr+++++====" + jsonstr);
        return jsonstr;
    }

}